package com.yeu;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet("/UpdataUserInfo")
public class UpdataUserInfo extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public UpdataUserInfo() {
		super();
	}

	/** 获取真实用户IP **/
	public String getRemortIP(HttpServletRequest request) {
		if (request.getHeader("x-forwarded-for") == null) {
			return request.getRemoteAddr();
		} else {
			return request.getHeader("x-forwarded-for");
		}
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("Get");
/*		try {
			Connection connect = DBUtil.getConnect();
			Statement statement = (Statement) connect.createStatement();
			String sqlInsertPass = "insert into " + DBUtil.TABLE_PASSWORD + "(userAccount,userPassword) values('abc','123')";
			statement.executeUpdate(sqlInsertPass);
			System.out.println("成功！");
		} catch (SQLException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}*/
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8"); // 设置响应报文的编码格式
		PrintWriter pw = response.getWriter(); // 获取 response 的输出流
		String userNumber = "";
		String userName = request.getParameter("userName");
		String userSex = request.getParameter("userSex");
		String userAge = request.getParameter("userAge");
		//String userPhone = request.getParameter("userPhone");
		//String userHead = request.getParameter("userHead");
		String userBirthday = request.getParameter("userBirthday");
		String userQQ = request.getParameter("userQQ");
		String userEmail = request.getParameter("userEmail");
		String homeAddress = request.getParameter("homeAddress");
		String introduction = request.getParameter("introduction");
		String ipAddress = getRemortIP(request);
		Cookie[] mCookie = request.getCookies();
		String mLog = null;
		System.out.println("userName:" + userName  + "\nipAddress:" + ipAddress); // 打印出来看一看
		System.out.println("【-- 更新用户信息--】");

		String resCode = "";
		String resMsg = "";
		String userId = "";

		/* 更新模块 */
		try {
			Connection connect = DBUtil.getConnect();
			Statement statement = (Statement) connect.createStatement(); // Statement可以理解为数据库操作实例，对数据库的所有操作都通过它来实现
			ResultSet result;
			if (mCookie != null) {
				for (Cookie cookie : mCookie) {
					if (cookie.getName().equals("userNumber")) {
						userNumber = cookie.getValue();
						
					}
				}
				
			}else {
				pw.println("请先登录！"); // 通过输出流把业务逻辑的结果输出
				pw.flush();
				return;
			}
			String sqlQuery = "select * from " + DBUtil.TABLE_USER_INFO + " where userNumber='" + userNumber + "'";
			// 查询类操作返回一个ResultSet集合，没有查到结果时ResultSet的长度为0
			result = statement.executeQuery(sqlQuery); // 先查询同样的账号（比如手机号）是否正确
			if (result.next()) { // 已存在 result.next()
				sqlQuery = "update " + DBUtil.TABLE_USER_INFO + " set userName = '" + userName + "',userSex = '" + userSex + "',userAge = '" + userAge + "',userBirthday = '"+ userBirthday + "',userQQ = '"+ userQQ + "',userEmail = '"+ userEmail + "',homeAddress = '"+ homeAddress + "',introduction = '"+ introduction + "' where userNumber = '" + userNumber + "'";
				int row = statement.executeUpdate(sqlQuery); // 判断用户信息是否更新成功
				if (row == 1) {
					//将日志信息插入日志表
					mLog = "更新成功";
					String sqlInsertLog = "insert into " + DBUtil.TABLE_USER_LOG + "(requestAccount,requestPassWord,requestIP,status) values('','','" + ipAddress + "','" + mLog + "')";
					statement.executeUpdate(sqlInsertLog);
					
					resCode = "400";
					resMsg = "更新成功！";
					userId = "";
					
				} else {
					//将日志信息插入日志表
					mLog = "更新失败";
					String sqlInsertLog = "insert into " + DBUtil.TABLE_USER_LOG + "(requestAccount,requestPassWord,requestIP,status) values('','','" + ipAddress + "','" + mLog + "')";
					statement.executeUpdate(sqlInsertLog);
					
					resCode = "402";
					resMsg = "更新失败！";
					userId = "";
					pw.println("更新失败！"); // 通过输出流把业务逻辑的结果输出
					pw.flush();
				}

			} else { // 帐号不存在
				//将日志信息插入日志表
				mLog = "帐号错误";
				String sqlInsertLog = "insert into " + DBUtil.TABLE_USER_LOG + "(requestAccount,requestPassWord,requestIP,status) values('','','" + ipAddress + "','" + mLog + "')";
				statement.executeUpdate(sqlInsertLog); // 插入帐号密码
				
				resCode = "401";
				resMsg = "当前账户不存在！";
				userId = "";
				pw.println("当前账户不存在！"); // 通过输出流把业务逻辑的结果输出
				pw.flush();
			}
			//断开数据库连接
			statement.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		response.sendRedirect("Index");
	}

}